package org.jeecg.modules.solitaire_app.wxpay;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.solitaire_app.app.entity.YsyMealOrder;
import org.jeecg.modules.solitaire_app.app.entity.YsyUsers;
import org.jeecg.modules.solitaire_app.app.mapper.YsyMealOrderMapper;
import org.jeecg.modules.solitaire_app.app.mapper.YsyUsersMapper;
import org.jeecg.modules.solitaire_app.wxpay.v3.Util;
import org.jeecg.modules.solitaire_app.wxpay.v3.WXConst;
import org.jeecg.modules.solitaire_app.wxpay.v3.WXPayParams;
import org.jeecg.modules.solitaire_app.wxpay.v3.WXReturnPayParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app/wxpay")
@Slf4j
@Api(tags = "微信支付")
public class WxPayController {

    @Autowired
    private WxPayCommon wxPayCommon;
    @Autowired
    private YsyMealOrderMapper ysyMealOrderMapper;
    @Autowired
    private YsyUsersMapper ysyUsersMapper;


    /*
     * 退款
     * */
    @PostMapping("/returnPay")
    @AutoLog(value = "微信支付-退款")
    @ApiOperation(value = "微信支付-退款", notes = "驻场申请-退款")
    public Result<?> returnPay(@RequestBody WXReturnPayParams wxReturnPayParams) throws IOException {
        return wxPayCommon.returnPay(wxReturnPayParams);
    }


    /*
     * 订单支付
     * */
    @PostMapping("/wxPay")
    @AutoLog(value = "微信支付-支付")
    @ApiOperation(value = "微信支付-支付", notes = "驻场申请-支付")
    public Result<?> sendOutPay(@RequestBody WXPayParams wxPayParams) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        return wxPayCommon.wxPay(wxPayParams);
    }

    /*支付回调*/
    @PostMapping("/wxPayNotify")
    public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("进入支付回调");
        Result<?> result = new Result<>();
        Map<String, String> map = new HashMap<>(12);
        String resultData = Util.readData(request);
        try {
            // 需要通过证书序列号查找对应的证书，verifyNotify 中有验证证书的序列号
            String plainText = Util.verifyNotify(resultData, WXConst.key);
            if (StrUtil.isNotEmpty(plainText)) {
                response.setStatus(200);
                map.put("code", "SUCCESS");
                map.put("message", "SUCCESS");
            } else {
                response.setStatus(500);
                map.put("code", "ERROR");
                map.put("message", "签名错误");
            }
            response.setHeader("Content-type", ContentType.JSON.toString());
            response.getOutputStream().write(JSONUtil.toJsonStr(map).getBytes(StandardCharsets.UTF_8));
            response.flushBuffer();
            //交易状态
            String trade_state = JSONObject.fromObject(plainText).getString("trade_state");
            //自定义参数
            String attach = JSONObject.fromObject(plainText).getString("attach");
            //微信支付订单号
            String transactionId = JSONObject.fromObject(plainText).getString("transaction_id");
            log.info("自定义参数{}", attach);
            log.info("交易订单号{}", transactionId);
            if (trade_state.equals("SUCCESS")) {
                String[] attachSplit = attach.split("&");
                //订单id
                String orderId = attachSplit[0];
                log.info("订单id{}", orderId);
                //订单来源
                String sourceType = attachSplit[1];
                log.info("订单来源{}", sourceType);
                //支付方式
                String payType = attachSplit[2];
                log.info("支付方式{}", payType);

                //写业务逻辑
                YsyMealOrder ysyMealOrder = ysyMealOrderMapper.selectOne(Wrappers.<YsyMealOrder>lambdaQuery()
                        .eq(YsyMealOrder::getId, orderId));

                if (ObjectUtil.isNotNull(ysyMealOrder)) {

                    //添加用户的次数
                    YsyUsers ysyUsers = ysyUsersMapper.selectOne(Wrappers.<YsyUsers>lambdaQuery()
                            .eq(YsyUsers::getId, ysyMealOrder.getUserId()));

                    ysyMealOrder.setStatus(1);
                    ysyMealOrder.setPayType(Integer.parseInt(payType));
                    ysyMealOrder.setUserPhone(ysyUsers.getPhone());
                    ysyMealOrder.setUserName(ObjectUtil.isNull(ysyUsers.getRealName())
                            ? ysyUsers.getNickName()
                            : ysyUsers.getRealName());
                    ysyMealOrderMapper.updateById(ysyMealOrder);

                    if (ObjectUtil.isNotNull(ysyUsers)) {
                        if (ysyMealOrder.getSourceType() == 1){
                            ysyUsers.setSealCarNum(ysyUsers.getSealCarNum() + ysyMealOrder.getCountNum());
                        }else{
                            ysyUsers.setDrivingTrackNum(ysyUsers.getDrivingTrackNum() + ysyMealOrder.getCountNum());
                        }
                        ysyUsersMapper.updateById(ysyUsers);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /*
     * 退款回调
     * */
    @PostMapping("/returnPayNotify")
    public void returnPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result<?> result = new Result<>();
        Map<String, String> map = new HashMap<>(12);
        String resultData = Util.readData(request);
        try {
            // 需要通过证书序列号查找对应的证书，verifyNotify 中有验证证书的序列号
            String plainText = Util.verifyNotify(resultData, WXConst.key);
            if (StrUtil.isNotEmpty(plainText)) {
                response.setStatus(200);
                map.put("code", "SUCCESS");
                map.put("message", "SUCCESS");
            } else {
                response.setStatus(500);
                map.put("code", "ERROR");
                map.put("messagdjdjdne", "签名错误");
            }
            response.setHeader("Content-type", ContentType.JSON.toString());
            response.getOutputStream().write(JSONUtil.toJsonStr(map).getBytes(StandardCharsets.UTF_8));
            response.flushBuffer();
            //退款状态
            String trade_state = JSONObject.fromObject(plainText).getString("refund_status");
            //微信支付订单号
            String transactionId = JSONObject.fromObject(plainText).getString("transaction_id");
            if (trade_state.equals("SUCCESS")) {
                //修改订单得状态为已退款
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        clipVideo("https://oss.pinzhuorj.com/app/mda-mcjm50zbmckqbcwt.mp4?Expires=1674790744&OSSAccessKeyId=TMP.3KdTcFGi9Z42xcZ3TiYhG3soKKApBkr1QMpo7RPU1CeUbe5a8bhUUa971Fz23EAa6wVKrBU55PHYhD3GFFHGXVYJtoWgR6&Signature=yp3uXaGItNtL6NEuIHhCiBPAQuM%3D", "D:\\test.mp4", "00:00:00", "00:00:30", "192.168.31.179", "8880");
    }

    public static int clipVideo(String videoPathName, String alarmVideo, String startDate, String stopDate, String mediaServerIp, String mediaServerHttpPort) {
        try {
            String clipVideoUrl = "http://" + mediaServerIp + ":" + mediaServerHttpPort + "/" +
                    "clipVideo?src_video=" + videoPathName + "&dst_video=" + alarmVideo + "&start_time=" + startDate + "&end_time=" + stopDate;
            System.out.println("clipVideo cut alarm video url ：" + clipVideoUrl);
            RestTemplate client = new RestTemplate();
            String clipResult = client.getForEntity(clipVideoUrl, String.class).getBody();
            System.out.println("clipVideo result：" + clipResult);
            return 0;
        } catch (RestClientException e) {
            System.out.println("cutAlarmVideo err  e：" + e.getMessage());
            throw new RestClientException("clipVideo 报错", e);
        }
    }

}
